package com.sky.service.impl;

import com.google.gson.Gson;
import com.sky.entity.futu.Deal;
import com.sky.entity.futu.StockOption;
import com.sky.entity.futu.StockOptionInfo;
import com.sky.utils.HttpUtil;
import com.sky.utils.UrlBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class FutuMarketService {

    private final Gson gson = new Gson();
    @Value("${futu.base-url}")
    private String BASE_URL;
    private final String prefix = "/market";

    // 拼接 BASE_URL 和 prefix
    private String getBaseUrlWithPrefix() {
        return BASE_URL + prefix;
    }
    @Autowired
    private HttpUtil httpUtil;

    public List<StockOption> getQuotesList(String code) throws IOException {
        String url = new UrlBuilder(getBaseUrlWithPrefix()  + "/get_quotes_list")
                .addParam("code", code).build();
        List<StockOptionInfo> stockOptionInfos = httpUtil.getList(url, StockOptionInfo.class);
        List<StockOption> stockOptions = new ArrayList<>();
        for (StockOptionInfo stockOptionInfo : stockOptionInfos){
            stockOptions.add(convertToStockOption(stockOptionInfo));
        }
        return stockOptions;
    }

    private StockOption convertToStockOption(StockOptionInfo source) {
        StockOption stockOption = new StockOption();

        stockOption.setStockId(source.getStock_id());
        stockOption.setStockCode(source.getStock_owner());
        stockOption.setStockName(source.getName());
        stockOption.setCode(source.getCode());
        stockOption.setName(source.getName());
        stockOption.setStrikeTime(source.getStrike_time());
        stockOption.setStrikePrice(source.getStrike_price());
        stockOption.setPc(source.getOption_type());
        stockOption.setStatus(1);
        stockOption.setIsDeleted(0);

        // Set type based on stock_owner prefix
        String stockOwner = source.getStock_owner();
        if (stockOwner != null && stockOwner.startsWith("HK")) {
            stockOption.setType((byte) 1);  // 港股
        } else if (stockOwner != null && stockOwner.startsWith("US")) {
            stockOption.setType((byte) 11); // 美股
        }

        // Set codeFiu only for US stocks
        String code = source.getCode();
        if (code != null && code.startsWith("US")) {
            stockOption.setCodeFiu(code);
        }

        return stockOption;
    }

}
